<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;


class RedEnvelope extends Model
{

    

    

    // 表名
    protected $name = 'red_envelope';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
	    'status_text',
    ];
	
	const STATUS_WAIT = 0;
	const STATUS_RECEIVE = 1;
	
	public static $statusList = [
		self::STATUS_RECEIVE => '已领取',
		self::STATUS_WAIT => '待领取',
	];
	
	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = self::$statusList;
		return $list[$value] ?? '';
	}
	
	public function user() {
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function goods() {
		return $this->belongsTo('goods', 'goods_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 添加红包
	 * @param $userId
	 * @param $orderId
	 * @param $goodsId
	 * @param $orderGoodsId
	 * @param $amount
	 * @return int|string
	 */
	public function add($userId, $orderId, $goodsId, $orderGoodsId, $amount) {
		$data = [
			'user_id' => $userId,
			'order_id' => $orderId,
			'goods_id' => $goodsId,
			'order_goods_id' => $orderGoodsId,
			'amount' => $amount,
			'create_time' => time(),
			'update_time' => time()
		];
		return Db::name('redEnvelope')
			->insert($data);
	}



	public function receive($userId, $orderId) {
		
		$row = Db::name('redEnvelope')->where(['order_id' => $orderId, 'user_id' => $userId])
			->find();
		if(!$row) {
			$this->error = '红包记录不存在';
			return false;
		}
		
		if($row['status'] != self::STATUS_WAIT) {
			$this->error = '该红包已领取';
			return false;
		}
		
		
		$this->startTrans();
		try {
			$res = $this->save(['status' => self::STATUS_RECEIVE], ['id' => $row['id']]);
			if(!$res) {
				throw new Exception('更改红包状态出错');
			}
			
			$user = \app\admin\model\User::get($userId);
			$userRes = Db::name('user')
				->where(['id' => $userId])->setInc('money', $row['amount']);
			if(!$userRes) {
				throw new Exception('添加余额出错');
			}
			
			$fundsModel = new Funds();
			$fundsRes = $fundsModel->addRecord($userId, $row['amount'], $user['money'], $fundsModel::ACCOUNT_TYPE_BALANCE, $fundsModel::OPE_TYPE_PLUS, $fundsModel::TYPE_HB, $orderId);
			if(!$fundsRes) {
				throw new Exception('添加资金记录出错');
			}
			
			$this->commit();
			return true;
		}  catch (Exception $e) {
			$this->rollback();
			$this->error = $e->getMessage();
			return false;
		}
	}


}
